package bar.dark.lee.insert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.RadioDialogActivity;

public class InsertPostActivity extends SuperActivity
{
	public static final int REQUEST_CATEGORY = 0;
	public static final int REQUEST_CHECK = 1;
	public static final int REQUEST_CREDIT = 2;
	public static final int REQUEST_BANKBOOK = 3;
	
	private DBSQLite sql;
	
	private TextView balanceText;
	private TextView balanceMoney;
	private View creditView;
	private TextView creditTextView;
	private View outBankBookView;
	private TextView outKindTextView;
	private TextView outKindMoneyTextView;
	
	private View dateButton;
	private TextView dateTextView;
	private EditText money;
	private View memoView;
	private EditText memo;
	private Button insertButton;
	
	private ArrayList<String> creditList;
	private ArrayList<String> bankBookList;
	
	// 날짜
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private int linkId = -1;
	private int bankLink = -1;
//	private int firstBankRadio = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.insert_postmoney);
		
		setGoneTitle();
		
		initFindView();
		initClickListener();
		initDataSetting();
	}

	@Override
	protected void onResume() 
	{
		super.onResume();
	}
	
	private void initFindView()
	{
		balanceText = (TextView) findViewById(R.id.InsertPostBalanceText);
		balanceMoney = (TextView) findViewById(R.id.InsertPostBalance);
		creditView = findViewById(R.id.InsertPostCreditView);
		creditTextView = (TextView) findViewById(R.id.InsertPostCreditKind);
		outKindTextView = (TextView) findViewById(R.id.InsertPostOutKind);
		outKindMoneyTextView = (TextView) findViewById(R.id.InsertPostOutKindMoney);
		
		dateButton = findViewById(R.id.InsertPostDate);
		dateTextView = (TextView) findViewById(R.id.InsertPostDateTextView);
		
		money = (EditText) findViewById(R.id.InsertPostMoney);
		EditTextInputFilter.filteringMoneyEditText(money);
		
		memoView = findViewById(R.id.InsertPostMemoView);
		memo = (EditText) findViewById(R.id.InsertPostMemo);
		insertButton = (Button) findViewById(R.id.InsertPostInsertButton);
		
		outBankBookView = findViewById(R.id.InsertPostOutBankBook);
	}
	
	private void initDataSetting()
	{
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
		toMonth = cal.get(Calendar.MONTH);
		toDay = cal.get(Calendar.DAY_OF_MONTH);
		
		dateTextView.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				creditList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					creditList.add(kind);
					c.moveToNext();
				}
				
				if (creditList.size() < 1)
				{
					String memo = "없음";
					creditList.add(memo);
					creditView.setClickable(false);
					creditView.setTag(false);
				}
				else
				{
					creditView.setClickable(true);
					creditView.setTag(true);
				}
				
				creditTextView.setText(creditList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				bankBookList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					bankBookList.add(kind);
					c.moveToNext();
				}
				
				if (bankBookList.size() < 1)
				{
					String memo = "없음";
					bankBookList.add(memo);
					outBankBookView.setClickable(false);
					outBankBookView.setTag(false);
				}
				else
				{
					outBankBookView.setClickable(true);
					outBankBookView.setTag(true);
				}
				
				outKindTextView.setText(bankBookList.get(0).toString());
			}
		});
		
		setBalanceCreditMoney();
	}
	
	private void initClickListener()
	{
		creditView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertPostActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, creditList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, creditTextView.getText().toString());
				startActivityForResult(intent, REQUEST_CREDIT);
			}
		});
		
		outBankBookView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertPostActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, bankBookList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, outKindTextView.getText().toString());
				startActivityForResult(intent, REQUEST_BANKBOOK);
			}
		});
		
		dateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				DatePickerDialog dpd = new DatePickerDialog(InsertPostActivity.this, new OnDateSetListener()
//				{
//					@Override
//					public void onDateSet(DatePicker view, int year, int monthOfYear,
//							int dayOfMonth)
//					{
//						dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
//						
//						toYear = year;
//						toMonth = monthOfYear;
//						toDay = dayOfMonth;
//					}
//				}, toYear, toMonth, toDay);
//				
//				dpd.show();
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
						
						toYear = year;
						toMonth = monthOfYear;
						toDay = dayOfMonth;
					}
				}, toYear, toMonth, toDay);
				
				cpd.show();
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (money.length() < 1)
				{
					BDUtil.showDialog(InsertPostActivity.this, "금액오류", "금액을 정확히 입력해주세요.");
					return;
				}
				
				if ((Boolean) creditView.getTag() == false)
				{
					BDUtil.showDialogManager(superContext, "신용카드가 하나도 없습니다.");
					return;
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag);
			}
		});
	}
	
	private void insertPostData()
	{
		creditOutInsert();
		
		sql.selectMapTile(InsertPostActivity.this, "SELECT money FROM bankbook WHERE name = '" + 
						BDUtil.getApostrophe(outKindTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.subtract(tempMoney);
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				String [] whereArgs = new String[]{outKindTextView.getText().toString()};
				sql.update(InsertPostActivity.this, "bankbook", map, "name = ?", whereArgs);
			}
		});
		
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		
		// 잔액을 입력한다.
		BalanceQuery balace = new BalanceQuery(superContext);
		balace.setBalance(BDConstents.BANK_TYPE, outKindTextView.getText().toString());
	}

	
	private boolean creditOutInsert()
	{
		setInOutTable(outKindTextView.getText().toString(), creditTextView.getText().toString(), "1");
		
		sql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '" 
				+ BDUtil.getApostrophe(creditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				int id = -1;
				int idIndex = c.getColumnIndex("id");
				int moneyIndex = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIndex);
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.subtract(tempMoney);
				
				if (id > 0)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("outmoney", money.toString());
					String [] whereArgs = new String[]{id + ""};
					sql.update(InsertPostActivity.this, "credit_card", map, "id = ?", whereArgs);
				}
				else
				{
					BDUtil.showDialog(InsertPostActivity.this, "신용카드에러", "신용카드 정보가 없습니다.");
				}
			}
		});
		
		return true;
	}
	
	private void setInOutTable(String moneyKind, String postMoneyKind, String type)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("category", BDConstents.CATEGORY_POST_OUT);
		
		map.put("outmoney", BDUtil.getCommaDel(money.getText().toString()));
		
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		map.put("date", date);
		map.put("moneykind", moneyKind);
		map.put("postmoneykind", postMoneyKind);
		map.put("type", type);
		
		map.put("memo", memo.getText().toString());
		
		sql.insert(this, map, "in_out");
	}
	
	private void setBankBookMoney()
	{
		sql.selectMapTile(this, "SELECT name, money FROM bankbook WHERE name = '" + 
				BDUtil.getApostrophe(outKindTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int nameIndex = c.getColumnIndex("name");
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				
				String name = "";
			//	int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				
				for (int i = 0; i < count; i++)
				{
					name = c.getString(nameIndex);
			//		money = money + Integer.parseInt(c.getString(moneyIndex));
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				outKindTextView.setText(name);
				outKindMoneyTextView.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	private void setBalanceCreditMoney()
	{
		bankLink = -1;
		
		sql.selectMapTile(this, "SELECT outmoney, banklink FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(creditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("outmoney");
				int bankLinkIndex = c.getColumnIndex("banklink");

				c.moveToFirst();
				
//				int outmoney = 0;
				BigDecimal outmoney = BigDecimal.ZERO;
				
				for (int i = 0; i < count; i++)
				{
//					outmoney = outmoney + Integer.parseInt(c.getString(columIndex));
					outmoney = outmoney.add(new BigDecimal(c.getString(columIndex)));
					bankLink = c.getInt(bankLinkIndex);
					c.moveToNext();
				}
				
				balanceText.setText("카드대금");
				balanceMoney.setText(BDUtil.getWon(outmoney.toString()) + shape);
			}
		});
		
		sql.selectMapTile(this, "SELECT name, money FROM bankbook WHERE id = " + 
							bankLink + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int nameIndex = c.getColumnIndex("name");
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				
				String name = "";
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				
				for (int i = 0; i < count; i++)
				{
					name = c.getString(nameIndex);
//					money = money + Integer.parseInt(c.getString(moneyIndex));
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				outKindTextView.setText(name);
				outKindMoneyTextView.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CREDIT)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				creditTextView.setText(selectData);
				
				setBalanceCreditMoney();
			}
		}
		else if (requestCode == REQUEST_BANKBOOK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				outKindTextView.setText(selectData);
				
				setBankBookMoney();
			}
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(InsertPostActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				try
				{
					sql.beginTansaction(superContext);
					
					insertPostData();
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) {
						return -1;
					}
				}
			}
			else
			{
				return arg0[0];
			}
			
			return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0) {
				BDUtil.showDialogFinish(InsertPostActivity.this, "확인", "입력이 완료 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
